package com.jianyun.jyzs.constant;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.dao.UserDao;
import com.jianyun.jyzs.fragment.ContactFragment;
import com.jianyun.jyzs.http.ContactModuleFmAsyncTask;
import com.jianyun.jyzs.utils.AsyncTaskFmUtil;
import com.jianyun.jyzs.utils.HttpResultFmVO;
import com.jianyun.jyzs.utils.LoginCache;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.jianyun.jyzs.http.ContactModuleFmAsyncTaskGet.object2Users;

@SuppressWarnings("unused")
public class ContactModuleFmHandler extends Handler {

    private ContactFragment fm;

    private ContactModuleFmHandler() {
        super();
    }

    // 带有Looper参数的构造函数
    private ContactModuleFmHandler(Looper L) {
        super(L);
    }

    public ContactModuleFmHandler(ContactFragment fm) {
        this.fm = fm;
    }

    int j=1;
    @SuppressLint("DefaultLocale")
    @Override
    public void handleMessage(Message msg) {
        if (msg.arg1 == 1) {
            Log.i("test", "收到通知");
           // fm.adapter.notifyDataSetChanged();
        }


        HttpResultFmVO vo = null;
        if (msg.getData() != null) {
            Bundle bundle = msg.getData();
            vo = (HttpResultFmVO) bundle.getSerializable(SysConstant.msg_key_parcelable);
        }
        if (vo != null && !vo.isNormal) {
            Toast.makeText(fm.getActivity(), vo.err, Toast.LENGTH_SHORT).show();
//            if (fm.dialog != null && fm.dialog.isShowing()) {
//                fm.dialog.dismiss();
//            }
            return;
        }
        try {
            JSONObject object = new JSONObject(vo.json);
            if (object.getBoolean("result")) {//正常返回
                List<User> users = object2Users(object, "");
                UserDao udao = new UserDao(fm.getActivity());
                if (object.getInt("pageIndex") == 1) {
//                    fm.contactList.clear();
//                    udao.deleteAllContact(fm.enterpriseCode, fm.userId);
                }
                if (object.getInt("pageIndex") < object.getInt("pageCnt")) {
                    AsyncTaskFmUtil atfu = new AsyncTaskFmUtil();
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("method", fm.act.getString(R.string.http_url_contact_method)));
//                    params.add(new BasicNameValuePair("enterpriseCode", fm.enterpriseCode));
//                    params.add(new BasicNameValuePair("id", fm.userId));
                    params.add(new BasicNameValuePair("pageIndex", (object.getInt("pageIndex") + 1) + ""));
                   // atfu.execute(fm.mHandler, LoginCache.getInstance().getLoginCache().getErpHttpUrl() + fm.act.getResources().getString(R.string.http_url_common), params);

                }

                if (users != null) {
                    for (User user : users) {

                        //user.setUserId(fm.userId);
                        //user.setEnterpriseCode(fm.enterpriseCode);
                        //Log.i("test", "user:" + user.toString());
//							new UserDao(act).deleteOneContact(user.getEnterpriseCode(), user.getUserId(),user.getServerUserId());
                        udao.insert(user);//存库

                        Log.e("err","通讯录第："+j);
                        j++;
//						if (Character.isDigit(user.getNameZh().charAt(0))) {
//							user.setHeader("#");
//						} else {
//							user.setHeader(CommonUtils.getFirstChar(user.getNameZh()));
//							char header = user.getHeader().toLowerCase().charAt(0);
//							if (header < 'a' || header > 'z') {
//								user.setHeader("#");
//							}
//						}
//			        	fm.contactList.add(user);
                    }
                }
                try {

                    if (object.getInt("pageIndex") < object.getInt("pageCnt")) {

                    } else {
//				if(fm.tv_selContacts.getText().toString().equals(fm.getString(R.string.text_allContact))){
                        fm.act.isCommonContact = false;
                       // fm.tv_selContacts.setText(fm.act.getString(R.string.text_commonContact));
//			        // 对list进行排序
//			        Collections.sort(fm.contactList, fm.new PinyinComparator() {});
//			        
//					fm.adapter = new ContactModuleFmAdapter(fm.act, R.layout.item_contact_list,fm.contactList);
//					fm.listView.setAdapter(fm.adapter);
//					fm.processContactList(users);
//
//    		       if(fm.contactList.size() > 10){
//    		    	   fm.tv_total.setText(String.valueOf(fm.contactList.size())+"位联系人");
//    		       }else{
//    		    	   fm.tv_total.setText("");
//    		       }

//        		}else{
//        			fm.act.isCommonContact = true;
//        			fm.tv_selContacts.setText(fm.getString(R.string.text_commonContact));
//        			fm.adapter = new ContactModuleFmAdapter(fm.act,R.layout.item_contact_list,fm.users_temp);
//        			fm.listView.setAdapter(fm.adapter);
//        			fm.tv_total.setText(String.valueOf(count)+"位常用联系人");
//        		}
                        Toast.makeText(fm.getActivity(), fm.getActivity().getString(R.string.action_contacts_update), Toast.LENGTH_LONG).show();
//                        if (fm.dialog != null && fm.dialog.isShowing()) {
//                            fm.dialog.dismiss();
//                        }
                        ContactModuleFmAsyncTask fmTask = new ContactModuleFmAsyncTask();
                        fmTask.execute(fm);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("err", "错误");
                }
            } else {
                Toast.makeText(fm.getActivity().getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
//                if (fm.dialog != null && fm.dialog.isShowing()) {
//                    fm.dialog.dismiss();
//                }
            }
        } catch (Exception e) {
            Log.e("err", "2错误");
            e.printStackTrace();
        }
    }

}
